package com.nopay.dxdwphone.ui.ativity;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.widget.ListView;

import com.alipay.sdk.app.PayTask;
import com.azhon.basic.eventbus.MessageEvent;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.dxdwphone.base.BaseActivity;
import com.nopay.dxdwphone.bean.CommonResponse;
import com.nopay.dxdwphone.bean.request.AlipayOrderRequest;
import com.nopay.dxdwphone.bean.response.LoginResponse;
import com.nopay.dxdwphone.bean.response.VIPResponse;
import com.nopay.dxdwphone.bean.response.WePayOrderResponse;
import com.nopay.dxdwphone.dialog.DialogLoading;
import com.nopay.dxdwphone.dialog.DialogPayResult;
import com.nopay.dxdwphone.dialog.PayMethodPopup;
import com.nopay.dxdwphone.utils.PayResult;
import com.nopay.dxdwphone.wx.WXSDKManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;
import com.nopay.dxdwphone.databinding.ActivityRechargeBinding;

import com.nopay.dxdwphone.ui.adapter.VIPAdapter;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ProjectName: myVisualPhone
 * @Package: cn.cn.myvisualphone.ui.ativity
 * @ClassName: ForgetActivity
 * @Description: 更新用户姓名
 * @Author: anqi
 * @CreateDate: 2021/5/23 8:05
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/5/23 8:05
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class RechargeActivity extends BaseActivity<ActivityRechargeBinding> {

    private VIPAdapter adapter;
    private DialogLoading mLoading;

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        binding.rlRoot.setPadding(0, getStatusBarHeight(RechargeActivity.this), 0, 0);
        binding.ivBack.setOnClickListener(v -> mSwipeBackHelper.backward());

        ListView lv_vip = findViewById(R.id.lv_vip);
        adapter = new VIPAdapter(RechargeActivity.this);
        lv_vip.setAdapter(adapter);
        lv_vip.setOnItemClickListener((parent, view, position, id) -> {
            boolean isSelected = adapter.getItem(position).isSelected();
            for (int i = 0; i < adapter.getCount(); i++) {
                adapter.getItem(i).setSelected(i == position && !isSelected);
            }
            adapter.notifyDataSetChanged();
        });

        api.doGetMemberConfig().enqueue(new Callback<VIPResponse>() {
            @Override
            public void onResponse(Call<VIPResponse> call, Response<VIPResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        adapter.addList(response.body().getData());
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<VIPResponse> call, Throwable t) {
                ToastUtils.showShort(RechargeActivity.this.getResources().getString(R.string.call_api_error));
            }
        });

        binding.btnOpenVip.setOnClickListener(v -> {
            VIPResponse.Data vipData = adapter.getSelectedVIP();
            if(vipData == null) {
                ToastUtils.showShort("请选择一个会员类型");
                return;
            }

            new PayMethodPopup(RechargeActivity.this)
                    .apply()
                    .setOrderTitle("电销大王-会员充值-" + vipData.getMemberLevel())
                    .setOrderAmount("¥" + vipData.getPrice())
                    .setOnPayListener(payMethod -> {
                        if(mLoading == null) mLoading = new DialogLoading(RechargeActivity.this);
                        mLoading.show("获取支付订单中...");

                        if(payMethod == PayMethodPopup.PAY_METHOD_WE) {
                            // TODO 微信支付
                            createWepayOrder(vipData);
                        }

                        if(payMethod == PayMethodPopup.PAY_METHOD_ALI) {
                            // TODO 支付宝支付
                            createAlipayOrder(vipData);
                        }
                    })
                    .setOnCancelListener(() -> {
                        ToastUtils.showShort("取消支付");
                    })
                    .showAtLocation(binding.rlRoot, Gravity.BOTTOM, 0, 0);
        });
    }

    private void createAlipayOrder(VIPResponse.Data vipData) {
        AlipayOrderRequest bean = new AlipayOrderRequest();
        bean.setOut_trade_no(getOutTradeNo()); // 订单编号
        bean.setSubject("电销大王-会员充值-" + vipData.getMemberLevel()); // 订单名称
        bean.setTotal_amount(vipData.getPrice() + "");
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        bean.setBody("{\"phone\":\"" + phone + "\", \"memberId\":" + vipData.getId() + "L}");

        RequestBody body = getRequestBody(bean);
        api.doCreateAlipayOrder(body).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if(mLoading != null) mLoading.dismiss();
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        String orderInfo = response.body().getMsg();
                        gotoAliPay(orderInfo);
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if(mLoading != null) mLoading.dismiss();
                ToastUtils.showShort(RechargeActivity.this.getResources().getString(R.string.call_api_error));
            }
        });
    }

    private void createWepayOrder(VIPResponse.Data vipData) {
        String orderNo = getOutTradeNo();
        int amount = (int) (vipData.getPrice() * 100);
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        String body = "{\"phone\":\"" + phone + "\", \"memberId\":" + vipData.getId() + "L}";
        String orderTitle = "电销大王-会员充值-" + vipData.getMemberLevel();
        api.doCreateWepayOrder(orderNo, amount, body, orderTitle).enqueue(new Callback<WePayOrderResponse>() {
            @Override
            public void onResponse(Call<WePayOrderResponse> call, Response<WePayOrderResponse> response) {
                if(mLoading != null) mLoading.dismiss();
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        WePayOrderResponse.Data wePayReq = response.body().getData();
                        boolean payReqSuccess = WXSDKManager.sendPayReq(wePayReq);
                        Log.e("RechargeActivity", "微信支付请求结果：" + payReqSuccess);
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<WePayOrderResponse> call, Throwable t) {
                if(mLoading != null) mLoading.dismiss();
                ToastUtils.showShort(RechargeActivity.this.getResources().getString(R.string.call_api_error));
            }
        });
    }

    /**
     * 生产订单编号
     * @return
     */
    private static String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    private void gotoAliPay(final String orderInfo) {
        new Thread(() -> {
            PayTask aLiPay = new PayTask(RechargeActivity.this);
            Map<String, String> result = aLiPay.payV2(orderInfo, true);
            final PayResult payResult = new PayResult(result);
            runOnUiThread(() -> {
                if("9000".equals(payResult.getResultStatus())) {
                    // TODO 支付成功，立即刷新数据
                    ToastUtils.showShort("支付成功");
                    doGetUserInfo();
                } else if("8000".equals(payResult.getResultStatus()) || "6004".equals(payResult.getResultStatus())) {
                    // TODO 支付结果未知，弹出提示弹框
                    new DialogPayResult(RechargeActivity.this, new DialogPayResult.Options()
                            .setResult("订单支付中...")
                            .setConfirmText("支付成功")
                            .setCancelText("取消支付"))
                            .setOnPayConfirmListener(() -> {
                                // TODO 确认支付成功，刷新用户数据
                                doGetUserInfo();
                            }).show();
                } else {
                    new DialogPayResult(RechargeActivity.this, new DialogPayResult.Options()
                            .setResult(payResult.getMemo())
                            .setConfirmText("继续支付")
                            .setCancelText("关闭"))
                            .setOnPayConfirmListener(() -> {
                                // TODO 确认继续支付
                                gotoAliPay(orderInfo);
                            }).show();
                }
            });
        }).start();
    }

    private DialogLoading mDialogLoading;

    private void doGetUserInfo() {
        if(mDialogLoading == null) mDialogLoading = new DialogLoading(RechargeActivity.this);
        if(!mDialogLoading.isShowing()) mDialogLoading.show("会员信息同步中...");

        new Handler().postDelayed(() -> {
            Long userId = SPUtils.getInstance().getLong(Constants.SP_USER_ID, -1);
            api.doGetUserInfo(userId).enqueue(new Callback<LoginResponse>() {
                @Override
                public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                    mDialogLoading.dismiss();
                    if (response.body() != null) {
                        if (Constants.RESULT_OK.equals(response.body().getCode())) {
                            int status = response.body().getData().getStatus();
                            String memberLevel = response.body().getData().getMemberLevel();
                            String invalidTime = response.body().getData().getInvalidTime();
                            SPUtils.getInstance().put(Constants.SP_VIP_STATUS, status);
                            SPUtils.getInstance().put(Constants.SP_VIP_LEVEL, memberLevel);
                            SPUtils.getInstance().put(Constants.SP_VIP_INVALID_TIME, invalidTime);
                            EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_CHANGE_VIP_STATUS));
                            mSwipeBackHelper.backward();
                        } else {
                            ToastUtils.showShort("会员数据同步出错，请联系客服");
                        }
                    } else {
                        ToastUtils.showShort("会员数据同步出错，请联系客服");
                    }
                }

                @Override
                public void onFailure(Call<LoginResponse> call, Throwable t) {
                    mDialogLoading.dismiss();
                    ToastUtils.showShort("会员数据同步出错，请联系客服");
                }
            });
        }, 1000);
    }

    @Override
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataEvent(MessageEvent msg) {
        super.onDataEvent(msg);
        if(msg.msgType == MessageEvent.TYPE_WE_PAY_RESULT) {
            int code = (int) msg.data[0];
            ToastUtils.showShort(msg.data[1].toString());
            if(code == 0) {
                doGetUserInfo();
            }
        }
    }
}
